package com.gitee.ice1938.swagger2staticdocs.petstore.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.nio.file.Paths;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.MarkupLanguage;
import io.github.swagger2markup.OpenAPI2MarkupConverter;
import io.github.swagger2markup.OpenSchema2MarkupConfig;
import io.github.swagger2markup.config.builder.OpenAPI2MarkupConfigBuilder;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;

@Controller
public class SwaggerStaticDocController {
   
    @RequestMapping(path="/swagger-doc.html", method = GET)
    public String swaggerDoc()   {
        
     // 输出Ascii格式
        OpenSchema2MarkupConfig config = new OpenAPI2MarkupConfigBuilder()
                .withSwaggerMarkupLanguage(MarkupLanguage.ASCIIDOC)
//              // 生成Markdown格式文档 .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.EN).withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples()
                .withoutInlineSchema().build();
        // ./target/asciidoc/generated
        String generatedDir = System.getProperty("generated.asciidoc.directory");
        if(generatedDir==null) {
            generatedDir = "C://temp";
        }
        //generatedDir = ".\\target\\asciidoc\\generated";
        // "classpath:woshare-miniapp.json";//
        String swagger_input_url = System.getProperty("swagger.input.url");
        if(swagger_input_url==null) {
            swagger_input_url = "http://localhost:20002/v3/api-docs/Swagger%20Petstore";
        }
//      Resource re = new ClassPathResource("woshare-miniapp.json");//
//      swagger_input_url = re.getURL().toString();
        ParseOptions options = new ParseOptions();
        options.setResolve(true);
        SwaggerParseResult result = new OpenAPIV3Parser().readLocation(swagger_input_url, null, options);
        OpenAPI swagger = result.getOpenAPI();

        OpenAPI2MarkupConverter converter = OpenAPI2MarkupConverter.from(swagger).withConfig(config).build();
        converter.toFolder(Paths.get(generatedDir));
        return  "swagger-doc.html";
    }
}
